import { Question } from '../../types';

export interface ScoreResult {
  id: string;
  isCorrect: boolean;
}

export interface ScoreData {
  score: number;
  total: number;
  correct: number;
  wrong: number;
  results: ScoreResult[];
}

export const calculateScore = (
  questions: Question[],
  userAnswers: Map<string, string | string[]>
): ScoreData => {
  let correct = 0;
  const results: ScoreResult[] = questions.map(q => {
    const userAnswer = userAnswers.get(q.id);
    let isCorrect = false;

    if (q.type === 'choice' && Array.isArray(q.correctAnswer)) {
      // Multi choice comparison
      const userArr = Array.isArray(userAnswer) ? userAnswer : [];
      const correctArr = q.correctAnswer;
      // Sort both to compare content
      const sortedUser = [...userArr].sort();
      const sortedCorrect = [...correctArr].sort();
      isCorrect = JSON.stringify(sortedUser) === JSON.stringify(sortedCorrect);
    } else {
      // Single choice or Judge
      isCorrect = userAnswer === q.correctAnswer;
    }

    if (isCorrect) correct++;
    return { id: q.id, isCorrect };
  });

  return {
    score: Math.round((correct / questions.length) * 100),
    total: questions.length,
    correct,
    wrong: questions.length - correct,
    results
  };
};

export const sortQuestionsByType = (questions: Question[]): Question[] => {
  return [...questions].sort((a, b) => {
    const getWeight = (q: Question) => {
      if (q.type === 'judge') return 0;
      if (q.type === 'choice') {
        return Array.isArray(q.correctAnswer) ? 2 : 1;
      }
      return 3;
    };
    return getWeight(a) - getWeight(b);
  });
};